package com.china08.yxyapi.api.home.activity.marker;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.maker.YxyMakerWorks;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.marker.YxyMakerWorksRepository;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 创客 上传 报名文件
 * 
 * @author renruihu
 *
 */
@CrossOrigin
@RestController
public class MakerRegFileUploadController extends YxyApiBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MakerRegFileUploadController.class);

    @Value("${yx.storage.maker.file}")
    private String uploadBasePath;

    @Autowired
    private YxyMakerWorksRepository resourceRepository;

    @RequestMapping(value = "/api_yw/home/activity/competition/works/upload/regfile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestPart MultipartFile file,
            RespModel respModel) throws IOException {
        try {
            String md5 = DigestUtils.md5Hex(file.getBytes());

            String name = file.getOriginalFilename();

            List<YxyMakerWorks> findByMd5 = resourceRepository.findByRegistermd5(md5);

            // 优化数据存储
            YxyMakerWorks findByMd5Resource = null;
            if (CollectionUtils.isNotEmpty(findByMd5)) {
                findByMd5Resource = findByMd5.get(0);
            }

            String extension = FilenameUtils.getExtension(name);
            String location = null;
            long size = 0;
            if (findByMd5Resource != null) {
                location = findByMd5Resource.getRegisterFile();
            } else {
                String path = YxyResUtil.getPath();
                String savePath = uploadBasePath + path;
                size = file.getSize();
                File sf = new File(savePath);
                String realPath = sf.getPath() + File.separator + md5.substring(0, 2) + File.separator + md5 + "."
                        + extension;
                FileUtils.forceMkdir(sf);
                FileUtils.writeByteArrayToFile(new File(realPath), file.getBytes());
                location = path + "/" + md5.substring(0, 2) + "/" + md5 + "." + extension;
            }
            respModel.md5 = md5;
            respModel.location = location;
            respModel.name = name;
            respModel.size = size;
        } catch (Exception e) {
            respModel.success = false;
            respModel.msg = e.getMessage();
        }
        return respModel;
    }

    protected static class RespModel extends YxyApiRespModel {
        public String md5;
        public String location;
        public String name;
        public long size;
        public boolean success = true;
        public String msg;
    }

}
